package com.lp.common.wechat;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaUserService;
import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor;
import com.lp.common.wechat.model.vo.PayParams;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * @program: biz
 * @description:
 * @author: Ke.Song
 * @since: 2024-04-07 21:42:01
 */
@Slf4j
@Service
public class WechatService {

    public static String appId;

    public static String mchId;

    @Autowired
    private WxMaService wxService;

    @Autowired
    private JsapiServiceExtension payService;

    @Value("${wx.env}")
    private String envVersion;

    public File getQrCode(String scene, String page) {
        File file = null;
        try {
            file = wxService.getQrcodeService().createWxaCodeUnlimit(scene, page,
                    false, envVersion, 430, false, new WxMaCodeLineColor(), true);
        } catch (Exception e) {
            log.error("二维码生成失败，message -> {}", e.getMessage());
        }
        return file;
    }

    public WxMaUserService getUserService() {
        return wxService.getUserService();
    }

    /** JSAPI支付下单 */
    public PrepayWithRequestPaymentResponse prepay(PayParams params) {
        log.info("支付下单：开始构建参数");
        PrepayRequest request = new PrepayRequest();
        request.setAppid(appId);
        request.setMchid(mchId);
        request.setDescription(params.getDescription());
        request.setOutTradeNo(params.getOutTradeNo());
        request.setTimeExpire(params.getTimeExpire());
        request.setNotifyUrl("https://www.yqxq.com.cn/api/biz/notify/transaction");

        Amount amount = new Amount();
        amount.setTotal(params.getAmountTotal());
        amount.setCurrency("CNY");
        request.setAmount(amount);

        Payer payer = new Payer();
        payer.setOpenid(params.getOpenid());
        request.setPayer(payer);
        log.info("支付下单：参数构建完成 -> {}", request);

        // 调用接口
        return payService.prepayWithRequestPayment(request);
    }
}
